<template>
    <div class="continer" v-loading="upimgLoding">
        <div class="topbox">
            <div>
                <el-button type="primary" @click="openWord">发布文章</el-button>
                <el-button icon="el-icon-refresh" @click="getList">刷新列表</el-button>
            </div>
            <el-form :model="search" :inline="true" ref="sc" @submit.native.prevent>
                <el-form-item label="" prop="title">
                    <el-input type="text" v-model="search.title" placeholder="请输入文章标题"></el-input>
                </el-form-item>
                <el-form-item label="" prop="type_id">
                    <el-select v-model="search.type_id" placeholder="请选择文章类型">
                        <el-option
                        v-for="item in wordTypes"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" class="ml_10" @click="()=>{getList()}" native-type="submit">搜索</el-button>
                <el-button @click="resetForm('sc')">重置</el-button>
            </el-form>
        </div>
        <el-table v-loading="tableload" :data="listData" row-key="id" style="width:100%" default-expand-all stripe border>
            <el-table-column label="标题" prop="title"></el-table-column>
            <el-table-column label="发布者" prop="author"></el-table-column>
            <el-table-column label="类型">
                <template slot-scope="scope">
                    {{wordTypesKey[scope.row.type_id]}}
                </template>
            </el-table-column>
            <el-table-column label="标签" prop="tags"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="text" size="mini" @click="()=>{detail(scope.row)}">查看</el-button>
                    <el-button type="text" size="mini" @click="()=>{edit(scope.row)}">修改</el-button>
                    <el-button type="text" size="mini" @click="()=>{del(scope.row)}">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="listLen"
            :page-size="limit"
            @current-change="toPage"
            :current-page.sync="currentPage"
            class="txt_r mt_20"
        ></el-pagination>
        <!-- 表单 -->
        <el-dialog :title="word.formTitle" :visible.sync="showForm" width="1100px">
            <el-form
                :model="word"
                label-position="right"
                :rules="formRules"
                ref="word"
                label-width="80px"
            >
                <el-form-item label="封面图" prop="cover_img">
                    <el-upload
                        :action="BASE_URL+'/admin/file/upload/createfile'"
                        name="file"
                        :before-upload="upimgBefore"
                        :on-success="upimgSuccess2"
                        :on-error="upimgError"
                        :show-file-list="false"
                    >
                        <el-button v-if="!word.cover_img" size="small" type="primary" ref="btn">点击上传</el-button>
                        <img v-else :src="BASE_URL + '/' + word.cover_img" class="form-img" />
                    </el-upload>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input type="text" v-model="word.title" placeholder="请输入文章标题"></el-input>
                </el-form-item>
                <el-form-item label="作者" prop="author">
                    <el-input type="text" v-model="word.author" placeholder="请输入作者"></el-input>
                </el-form-item>
                <el-form-item label="文章类型" prop="type_id">
                    <el-select v-model="word.type_id" placeholder="请选择文章类型" class="w_100">
                        <el-option
                            v-for="item in wordTypes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <div class="quill_pb">
                        <!-- <quill-editor
                            v-model="word.content"
                            ref="myQuillEditor"
                            :options="editorOption"
                            class="editor"
                        ></quill-editor> -->
                        <vue-ueditor-wrap v-model="word.content" :config="ueConfig"></vue-ueditor-wrap>
                    </div>
                    <el-upload
                        class="dn"
                        :action="BASE_URL+'/admin/file/upload/createfile'"
                        name="file"
                        :before-upload="upimgBefore"
                        :on-success="upimgSuccess"
                        :on-error="upimgError"
                        >
                        <el-button size="small" type="primary" ref="btn">点击上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="标签" prop="tags">
                    <div
                        v-for="(item,index) in formTagsArr"
                        :key="index"
                        class="tag_txt"
                    >
                        {{item}}
                        <span class="close fs_20" @click="()=>{delTag(index)}">&times;</span>
                    </div>
                    <input v-if="word.tagsArr.length<3" type="text" class="tagipt" @keyup.enter="addTag" />
                    <span class="ml_10 c_99">按回车Enter创建标签（{{word.tagsArr.length}}/3）</span>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showForm = false">取 消</el-button>
                <el-button v-if="word.isEdit" type="primary" @click="editWord">修 改</el-button>
                <el-button v-else type="primary" @click="addWord">发 布</el-button>
            </div>
        </el-dialog>
        <el-dialog title="" :visible.sync="showDetail" width="1100px">
            <div class="word">
                <div class="title">{{detailData.title}}</div>
                <div class="info mt_20">
                    <div>发布者：{{detailData.author}}</div>
                    <div class="infoafter">
                        <span>{{detailData.create_time}}</span>
                        <span>浏览量：{{detailData.read}}</span>
                    </div>
                </div>
                <div class="cont ql-editor mt_20" v-html="detailData.content"></div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor';
import VueUeditorWrap from 'vue-ueditor-wrap';
import { BASE_URL } from "../../config/app";
import * as apis from "../../api/article/article";

export default {
    data() {
        return {
            tableload:false,
            listData:[],
            // 分页
            listLen: 0,
            limit: 14,
            currentPage: 1,
            // 详情
            showDetail: false,
            detailData: {},
            // 文章
            word:{
                formTitle: "发布文章",
                isEdit: false,
                cover_img: "",
                title: "",
                type_id: "",
                content: "",
                tags: "",
                tagsArr: []
            },
            showForm: false,
            BASE_URL: "",
            fileName: "",
            upimgLoding: false,
            editorOption: {
                modules: {
                    toolbar: {
                        container: [
                            ['bold', 'italic', /*'underline', 'strike'*/],
                            ['blockquote', 'code-block'],
                            [{'list': 'ordered'}, {'list': 'bullet'}],
                            [{'size': ['small', false, 'large', 'huge']}],
                            [{'color': []}, {'background': []}],
                            [{'align': []}],
                            ['link', 'image']
                        ],
                        handlers: {
                            'image': ()=> {
                                this.fileName = this.$store.state.userName + "_" + Date.now();
                                this.$refs.btn.$el.click();
                            }
                        }
                    }
                },
                placeholder: "请输入文章内容"
            },
            formRules: {
                title: [{required: true,message: "请输入标题",trigger: "blur"}],
                author: [{required: true,message: "请输入作者",trigger: "blur"}],
                type_id: [{required: true,message: "请选择文章类型",trigger: "change" }],
                content: [{required: true,message: "请输入文章内容",trigger: "blur"}],
            },
            // 搜索
            search:{
                title: "",
                type_id: ""
            },
            wordTypes:[
                {value:"1", label:"资讯"},
                {value:"2", label:"政策"},
                {value:"3", label:"需求"},
            ],
            wordTypesKey:{
                "1":"资讯",
                "2":"政策",
                "3":"需求"
            },
            // 百度编辑器
            ueditorMsg: '',
            ueConfig: {
                // 初始容器高度
                initialFrameHeight: 300,
                // 初始容器宽度
                initialFrameWidth: '100%',
                // 上传文件接口
                elementPathEnable: false,
                wordCount: false,
                UEDITOR_HOME_URL: '/UEditor/',
                imageActionName: 'uploadimage', //执行上传图片的action名称,
                imageFieldName: "file", //提交的图片表单名称
                imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
                "fileActionName": "uploadfile",
                "fileFieldName": "file",
                "fileAllowFiles": [
                    ".png", ".jpg", ".jpeg", ".gif", ".bmp",
                    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
                    ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
                    ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
                ],
            },
        };
    },
    created(){
        this.BASE_URL = BASE_URL;
        this.getList();
    },
    methods: {
        getList(page=1){
            this.tableload = true;
            apis.getList({
                ...this.search,
                page: page,
                per_page: this.limit
            }).then((data)=>{
                this.tableload = false;
                if(data.code){
                    this.$message.error(data.message);
                    return;
                }
                this.listLen = data.data.total;
                this.limit = data.data.per_page;
                this.listData = data.data.data;
            }).catch(()=>{
                this.tableload = false;
                this.$message({type: "error",message: "请求失败",duration: 1800});
            });
        },
        toPage(val){
            this.currentPage = val;
            this.getList(val);
        },
        edit(row){
            this.word = row;
            this.word.type_id = String(this.word.type_id);
            this.word.isEdit = true;
            this.word.formTitle = "修改";
            this.word.tagsArr = this.word.tags.split(",");
            this.showForm = true;
        },
        del(row){
            this.$confirm("确定删除该文章吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(()=>{
                apis.del({id:row.id}).then((data)=>{
                    if(data.code){
                        this.$message.error(data.message);
                        return;
                    }
                    this.$message.success("删除成功");
                    this.getList(this.currentPage);
                }).catch(()=>{
                    this.$message.error("删除失败");
                })
            }).catch(()=>{});
        },
        detail(row){
            this.detailData = row;
            var regex1 = new RegExp("(i?)(\<img)(?!(.*?style=['\"](.*)['\"])[^\>]+\>)","gmi");
            this.detailData.content = this.detailData.content.replace(regex1, `$2 style="display:block;max-width:100%!important;height:auto!important;"$3`);
            this.showDetail = true;
        },
        resetForm(name){
            this.$refs[name].resetFields();
        },
        // 插入图片
        upimgBefore(){ this.upimgLoding = true; },
        upimgSuccess(data){
            this.upimgLoding = false;
            let quill = this.$refs.myQuillEditor.quill;
            if (data.code) {this.$message.error('图片插入失败');return false;}
            let length = quill.getSelection().index; // 获取光标所在位置
            quill.insertEmbed(length, 'image', BASE_URL + "/" + data.data.key); // 插入图片
            quill.setSelection(length + 1); // 调整光标
        },
        upimgSuccess2(data){
            this.upimgLoding = false;
            this.word.cover_img = data.data.key;
            // let quill = this.$refs.myQuillEditor.quill;
            // if (data.code) {this.$message.error('图片插入失败');return false;}
        },
        upimgError(){
            this.upimgLoding = false;
            this.$message.error('图片插入失败');
        },
        // 发布
        openWord(){
            this.word = {
                formTitle: "发布文章",
                isEdit: false,
                cover_img: "",
                title: "",
                type_id: "",
                content: "",
                tags: "",
                tagsArr: []
            };
            this.showForm = true;
        },
        addTag(event){
            if(this.word.tagsArr.length>=3){
                this.$message.error("最多创建三个标签");
                return false;
            }
            let value = event.target.value;
            if(!value){return;}
            this.word.tagsArr.push(value);
            this.word.tags = this.word.tagsArr.join(",");
            event.target.value = "";
        },
        delTag(id){
            this.word.tagsArr.splice(id,1);
            this.word.tags = this.word.tagsArr.join(",");
        },
        addWord(){
            console.log(this.word)
            this.$refs['word'].validate((valid) => {
                if (!valid) {return false;}
                apis.add(this.word).then((data)=>{
                    if(data.code){
                        this.$message.error(data.message);
                        return false;
                    }
                    this.$message.success("发布成功");
                    this.showForm = false;
                    this.getList();
                }).catch(()=>{
                    this.$message.error("发布失败");
                })
            });
        },
        editWord(){
            this.$refs['word'].validate((valid) => {
                if (!valid) {return false;}
                apis.edit(this.word).then((data)=>{
                    if(data.code){
                        this.$message.error(data.message);
                        return false;
                    }
                    this.$message.success("修改成功");
                    this.showForm = false;
                    this.getList();
                }).catch(()=>{
                    this.$message.error("修改失败");
                })
            });
        }
    },
    computed: {
        formTagsArr(){
            let arr = this.word.tags.split(",");
            return arr.length===1&&arr[0]===""?[]:arr;
        }
    },
    components: {
        quillEditor,
        VueUeditorWrap
    }
};
</script>

<style scoped>
.continer{padding-bottom:62px;}
.editor{height:400px; color:#333; line-height:1.42;}
.dn{display:none;}
.w_100{width:100%;}

.ml_10{margin-left:10px;}
.txt_r {text-align: right;}
.topbox {margin-bottom: 20px;}
.detailTable{font-size:16px;}
.detailTable td{padding:4px 8px;}
.detailTable .tr{text-align:right;}
.topbox{display:flex; align-items:center; justify-content: space-between;}
.topbox .el-form-item{margin-bottom:0;}

.quill_pb{padding-bottom:46px;}
.tagipt{display:inline-block; padding:0 15px; width: 114px; height:30px; line-height:1; border:1px solid #DCDFE6; border-radius:16px; color:#606266;}
.tag_txt{display:inline-block; margin-right:10px; height:30px; line-height:30px; padding:0 10px 0 15px; border-radius:16px; background:#409EFF; color:#fff;}
.tag_txt>*{vertical-align:middle;}
.tag_txt .close{cursor:pointer; padding-left:10px;}
.form-img{max-width:140px; max-height:140px;}

.word{padding:20px;}
.word .title{font-size:20px; text-align: center;}
.word .info{display:flex; justify-content:flex-end; align-items: center; font-size:14px; color:#777777;}
.word .info .infoafter span{padding-left:2em;}
</style>
